package com.learn.jdk21.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@RestController
@RequestMapping("threadpoolreuse")
@Slf4j
public class ThreadPoolReuseService {

    /**
     * 平台线程泄露
     */
    public String threadPoolReuse() {
        return threadPoolReuse(ThreadPoolHelper.getThreadPool());
    }


    /**
     * 虚拟线程泄露
     */
    public String VirtualThreadPoolReuse() {
        return threadPoolReuse(ThreadPoolHelper.getVirtualThreadPool());
    }


    private String threadPoolReuse(ThreadPoolExecutor threadPool) {
        IntStream.rangeClosed(1, 10).forEach(i -> {
            threadPool.execute(() -> {
                String payload = IntStream.rangeClosed(1, 1000000)
                        .mapToObj(__ -> "a")
                        .collect(Collectors.joining("")) + UUID.randomUUID().toString();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                }
                log.debug(payload);
            });
        });
        return "OK";
    }

    static class ThreadPoolHelper {
        public static ThreadPoolExecutor getThreadPool() {
            return (ThreadPoolExecutor) Executors.newCachedThreadPool();
        }

        public static ThreadPoolExecutor getVirtualThreadPool() {
            return (ThreadPoolExecutor) Executors.newVirtualThreadPerTaskExecutor();
        }
    }
}
